package com.archer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

@WebServlet("/WebSocketServletByMe")
public class WebSocketServletByMe extends WebSocketServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private static Set<PushMessageInbound> connSet = new HashSet<>();

    @Override
    protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) {
        return new PushMessageInbound();
    }

    private final static class PushMessageInbound extends MessageInbound {
        @Override
        protected void onOpen(WsOutbound outbound) {
            super.onOpen(outbound);
            connSet.add(this);
            System.out.println("==== 连接打开" + connSet.size() + " ======");
            try {
                outbound.writeTextMessage(CharBuffer.wrap("<p><font color='blue'>欢迎来到极光工作室聊天室</font></p>"));
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        @Override
        protected void onClose(int status) {
            super.onClose(status);
            connSet.remove(this);
            System.out.println("==== 连接关闭 " + connSet.size() + "======");
        }

        @Override
        protected void onTextMessage(CharBuffer charBuffer) throws IOException {
            System.out.println("收到消息：" + charBuffer.toString());
            String content = charBuffer.toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = "";
            try {
                time = sdf.format(new Date());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            /*发送消息到客户端*/
            String msg = "<p>" + time + " | " + content + "</p>";
            sendMessageToOnline(msg);
        }

        @Override
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
        }
    }

    public static void sendMessageToOnline(String message) {
        try {
            for (PushMessageInbound conn : connSet) {
                conn.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
